// pages/main/live/live.js
import moment from '../../../utils/moment'
import req from '../../../utils/req'
import md5 from '../../../utils/md5'

const app = getApp()
moment.locale('zh-cn', {
  weekdays: '周日_周一_周二_周三_周四_周五_周六'.split('_')
})
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tab: ['预约直播', '我的预约'],
    tabIndex:0,
    show: 0, //0:隐藏1:邀请好友2:预约
    selectData: {}, //选择的数据
    shareId: '', //分享者id
    showcancle: false, //取消预约弹窗
    listData: [], //预约直播列表数据
    orderSuccess: false, //预约成功弹窗
    selectresult: {
      page: 1,
      size: 10,
    },
    mylistData: [], //我的预约列表
    hasmore: true,
    shareOrderSuccess: false,
    isself: false,
    showlist:[],//奖励弹窗数组
    showlistmask:false,
    modalNum: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      shareId: options.shareId || '',
    })

    if (!wx.getStorageSync('openid')) {
      wx.login({
        success: res => {
          wx.getUserInfo({
            withCredentials: true,
            success: (res_user) => {
              console.log(res_user);
              var object = {
                record_type: 1,
                auth_type: 0,
                scene_value: 0,
                code: res.code,
                encryptedData: encodeURIComponent(res_user.encryptedData),
                iv: encodeURIComponent(res_user.iv),
              }
              var sign = app.sort_ASCII(object)
              wx.request({
                url: app.globalData.new_url + '/user/login/login',
                data: {
                  record_type: 1,
                  auth_type: 0,
                  scene_value: 0,
                  code: res.code,
                  encryptedData: encodeURIComponent(res_user.encryptedData),
                  iv: encodeURIComponent(res_user.iv),
                  sign: sign,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                success: (res) => {
                  wx.setStorageSync('session', res.data.hash);
                  wx.setStorageSync('openid', res.data.openid);
                  wx.setStorageSync('open_id', res.data.open_id);

                  let isself = options.shareId == res.data.openid
                  this.setData({
                    isself: isself,
                    show: options.shareId && !isself ? 2 : this.data.show
                  })
                  options.shareId ? !isself ? this.getvidodetail(options.video_id) : this.getmyOrder() : this.getlist()
                  if (isself && options.shareId) {
                    this.setData({
                      tabIndex: 1
                    })
                  }
                }
              })
            },
          })
        },

      })
    } else {
      let isself = options.shareId == wx.getStorageSync('openid')
      this.setData({
        isself: isself,
        show: options.shareId && !isself ? 2 : this.data.show
      })
      options.shareId ? !isself ? this.getvidodetail(options.video_id) : this.getmyOrder() : this.getlist()
      if (isself && options.shareId) {
        this.setData({
          tabIndex: 1
        })
      }
    }
  },
  getvidodetail(id) {
    wx.getChannelsLiveNoticeInfo({
      finderUserName: id,
      success: res => {
        wx.getChannelsLiveInfo({
          finderUserName: id,
          success: res1 => {
            console.log(res1);
            if (res1.description) {
              res.description = res1.description
              res.live_id = res.noticeId
              res.start = moment(parseInt(res.startTime) * 1000).format(' M月DD日(dddd)  HH:mm')
              res.video_id = id
              this.setData({
                selectData: res,
                show: 2
              })
            }
          }
        })
      }
    })
  },

  // shareId=oQJ6q0hanj5kwWq3Ej2FEAFAuPwY&video_id=sphnzaDfetLbrF3

  // 获取直播间直播
  getlive(item) {
    let id = item.video_id
    wx.getChannelsLiveNoticeInfo({
      finderUserName: id,
      success: res => {

        if (item.record && item.record.live_id) {
          res.isorder =md5(res.noticeId)== item.record.live_id
        }

        res.start = moment(parseInt(res.startTime) * 1000).format(' M月DD日(dddd)  HH:mm')
        res.video_id = id
        wx.getChannelsLiveInfo({
          finderUserName: id,
          success: res1 => {
            if (res1.description) {
              res.description = res1.description
              this.data.listData.push(res)
              this.setData({
                listData: this.data.listData
              })
            }
          }
        })

        console.log(res);
        // wx.getChannelsLiveNoticeInfo()
      }
    })
  },
  inviteFriend(e) {

    this.setData({
      show: 1,
      selectData: this.data.mylistData[e.currentTarget.id]

    })
  },
  makeorder(e) {
    let id = this.data.listData[e.currentTarget.id].noticeId
    wx.reserveChannelsLive({
      noticeId: id,
      success: res => {
        if (res.state == 6) {
          this.submitOrder(id)
        }
      },
      fail: err => {
        console.log(err);
      }
    })
    this.setData({
      selectData: this.data.listData[e.currentTarget.id]
    })
  },
  cancleBtn() {
    this.setData({
      showcancle: false
    })
  },

  OnmodalNum:function({detail}, ggg){
    //这立的这个e就是子组件传过来的值
    this.setData({
      modalNum:detail==1?this.data.modalNum+1:this.data.modalNum-1
   })},


  getlist() {
    this.data.listData = []
    req.getVideoList().then(res => {
      res &&
        res.map(item => {
          this.getlive(item)
        })
    })
  },
  // 获取我的预约
  async getmyOrder() {
    // 获取数据
    req.getMysubscribe(this.data.selectresult).then(res => {
      if (this.data.selectresult.page == 1) {
        this.data.mylistData = []
      }
      res.map(item => {
        item.start = moment(parseInt(item.live_time) * 1000).format(' M月DD日(dddd)  HH:mm');
        // 直播时间是否在当前时间之前
        item.isshow = moment(parseInt(item.live_time) * 1000).isBefore(moment()) ? false : true
        if (item.reward != 1) {
          this.setData({
            mylistData: this.data.mylistData.concat(item),
          })
        } else {
          req.getSubscribeList({
            live_id: item.live_id
          }).then(res1 => {
            item.invite = []
            
            if (res1 && res1.length > 0) item.invite = res1
            this.setData({
              mylistData: this.data.mylistData.concat(item),
    
            })
          })
        }
      })
      this.setData({
        hasmore: !(res.length < this.data.selectresult.size)
      })

    }).catch(err => {
      console.log(err);
      if (err.data.code == 500) {
        wx.showToast({
          title: '暂无数据',
          icon: 'none'
        })
      }
    })
  },

  onReachBottom() {
    if (this.data.hasmore && this.data.tabIndex == 1) {
      let current = this.data.selectresult.page
      this.data.selectresult.page = current + 1
      this.getmyOrder()
    }
  },

  tabChange(e) {
    let id = e.currentTarget.id
    id == '1' &&
      wx.setNavigationBarTitle({
        title: '我的预约',
      })
    this.setData({
      tabIndex: id,
      selectresult: {
        page: 1,
        size: 10,
      }
    })
    id == 0 ? this.getlist() : this.getmyOrder()
  },

  submitOrder(id) {
    let {
      headUrl: video_headimg,
      nickname: video_name,
      startTime: live_time,
      description,
      video_id,
    } = this.data.selectData
    // req
    // .subscribeLive({
    //   video_id: 'sphnzaDfetLbrF3',
    //   video_headimg: 'https://wx.qlogo.cn/finderhead/IbQhd2Y9oKcWyibyLrlDueRiaertTpmOzibwALWM4JQP699QibF77icajjw/0',
    //   video_name: '气质范国际大牌张总',
    //   live_time: '1660818600',
    //   description: '全场大牌浮力，张总补贴1米免费song！',
    //   p_unionid: 'oQJ6q0vbHTy99jndDhwaZAo3RmgA',
    //   live_id: 'notice/UzFfAgtgekIEAQAAAAAAy_UICiFgcwAAAAstQy6ubaLX4KHWvLEZgBPG1TKW1_6IvxcvpLWERud2SHj9_VwwFZSU8wsFtRtlAV7S7fXbRwj5_CWGTU3XbxHEV8JXNyKdtt4keGPnfdsmDs8Aagy1n5sQQ_HR_1EgWe6UjxMdame9HX29sGepb-EtLzqbHhvNc0fqpoQLr0yWsD9K9HB1pRRA8mx7OgJ6Iikzuyq5qYNcDH6VdvYcQVwin8Kxq61fsw',
    // })
    req
      .subscribeLive({
        video_id,
        video_headimg,
        video_name,
        live_time,
        description,
        p_unionid: this.data.shareId,
        live_id: this.data.selectData.noticeId,
      }).then(res => {
        if (res.code == 200) {
          res && this.setData({
            orderSuccess: this.data.shareId ? false : true,
            shareOrderSuccess: this.data.shareId ? true : false,
            show: 0
          })
          this.data.shareId ? this.getmyOrder() : this.getlist()
          // this.getlive()
          setTimeout(() => {
            this.setData({
              shareOrderSuccess: false,
              tabIndex: this.data.shareId ? 1 : 0
            })
          }, 3000)
        } else {
          console.log(11111111111111111);
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration:5000
          })
        }

      })
  },

  close() {
    this.setData({
      orderSuccess: false,
      tabIndex: 1,
    })
  },
  hideHandle() {
    this.setData({
      show: 0
    })
    this.getlist()
  },
  onShareAppMessage() {
    let id = this.data.selectData.video_id || this.data.selectData.live_id
    return {
      title: '',
      path: `/pages/main/live/live?shareId=${wx.getStorageSync('openid')}&video_id=${id}`
    }
  }




})